package com.jing.ads.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;

import com.jing.ads.downloader.Constants;

import android.content.Context;
import android.os.Environment;

public class DDCrashHandler implements UncaughtExceptionHandler {

	private Thread.UncaughtExceptionHandler mDefaultHandler;
	private static DDCrashHandler INSTANCE;

	private DDCrashHandler() {
	}

	public static DDCrashHandler getInstance() {
		if (INSTANCE == null)
			INSTANCE = new DDCrashHandler();
		return INSTANCE;
	}

	public void init(Context ctx) {
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		final String msg = getCrashInfoToFile(ex);
		if (mDefaultHandler != null) {
			mDefaultHandler.uncaughtException(thread, ex);
		}
//		new Thread(new Runnable() {
//			
//			@Override
//			public void run() {
//				writeLog(msg);
//			}
//		}).start();
	}

	private void writeLog(String msg) {
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		try {
			String root = Environment.getExternalStorageDirectory().getPath();
			File base = new File(root + Constants.DEFAULT_DL_SUBDIR);
			if (!base.exists()) {
				base.mkdirs();
			}
			File crash = new File(base, "crash.txt");
			if (!crash.exists()) {
				crash.createNewFile();
			}
			fos = new FileOutputStream(crash, true);
			osw = new OutputStreamWriter(fos);
			bw = new BufferedWriter(osw);
			bw.write(msg);
			bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (osw != null) {
					osw.close();
				}
				if (bw != null) {
					bw.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private String getCrashInfoToFile(Throwable ex) {
		if (ex == null) {
			return null;
		}
		StringWriter info = null;
		PrintWriter printWriter = null;
		try {
			info = new StringWriter();
			printWriter = new PrintWriter(info);
			ex.printStackTrace(printWriter);
			Throwable cause = ex.getCause();
			while (cause != null) {
				cause.printStackTrace(printWriter);
				cause = cause.getCause();
			}
			return info.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (printWriter != null) {
					printWriter.close();
				}
				if (info != null) {
					info.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
